package cn.sytton.taffe.wx.helper;

import cn.sytton.taffe.framework.util.JsonUtil;
import cn.sytton.taffe.framework.util.WebClientUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class JsCode2session {

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;

    public Map<String, Object> getOpenId(String jsCode) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+jsCode+"&grant_type=authorization_code";
        String response = WebClientUtil.getDefaultWebClientBuilder().build()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .block();
        Map<String, Object> result = JsonUtil.getEntity(response);

        /*
        {
            "openid":"xxxxxx",
            "session_key":"xxxxx",
            "unionid":"xxxxx",
            "errcode":0,
            "errmsg":"xxxxx"
        }
        */

        return result;
    }
}
